package com.yanqu.road.server.cmd.relatives;

import com.yanqu.road.entity.relatives.RelativesInfo;
import com.yanqu.road.entity.relatives.RelativesLetter;
import com.yanqu.road.logic.pb.RelativesPb;
import com.yanqu.road.pb.relatives.RelativesProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.relatives.RelativesModule;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

import java.util.List;

@Cmd(code = Protocol.S_RELATIVES_GET_LETTER, desc = "获取书信列表")
public class GetLetterListCmd extends AbstractCommand {

	private long relativesId;
	private List<RelativesLetter> letters;
	private int writeLetterNum;
	private int receiveLetterNum;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		RelativesProto.LetterListReqMsg reqMsg = RelativesProto.LetterListReqMsg.parseFrom(packet.getBytes());
		relativesId = reqMsg.getRelativesId();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		RelativesInfo relativesInfo = player.getModule(RelativesModule.class).getRelativesInfo(relativesId);
		if (relativesInfo == null || relativesInfo.getStatus() == 0) {
			ret = GameErrorCode.E_RELATIVES_TIMES_NOT_ENOUGH;
			return;
		}
		if (relativesInfo.getUserId1() == player.getUserId()) {
			writeLetterNum = relativesInfo.getLetterNum1();
			receiveLetterNum = relativesInfo.getLetterNum2();
		} else {
			writeLetterNum = relativesInfo.getLetterNum2();
			receiveLetterNum = relativesInfo.getLetterNum1();
		}
		letters = player.getModule(RelativesModule.class).getAllLetters(relativesId);
	}

	@Override
	public void sendData(GamePlayer player) {
		RelativesProto.LetterListRespMsg.Builder respMsg = RelativesProto.LetterListRespMsg.newBuilder();
		if (ret == 0) {
			respMsg = RelativesPb.parseLetterListMsg(relativesId, writeLetterNum, receiveLetterNum, letters);
		}
		respMsg.setRet(ret);
		player.sendPacket(Protocol.U_RELATIVES_GET_LETTER, respMsg);
	}

}
